package com.bwie.common.handler;

import com.bwie.common.exception.AuthException;
import com.bwie.common.result.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler {



   private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(AuthException.class)
    public Result exceptionHandler(AuthException Exception, HttpServletRequest request){
        logger.error("请求URI：{}出现了异常，异常信息：{}",request.getRequestURI(),Exception.getMessage());
        return Result.error(Exception.getMessage());
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e,HttpServletRequest request)
    {
        logger.error("请求URI：{}出现了异常，异常信息：{}",request.getRequestURI(),e.getMessage());
        String collect = e.getBindingResult().getFieldErrors().stream().map(fieldError -> fieldError.getDefaultMessage())
                .collect(Collectors.joining(";"));
        return Result.error(collect);
    }

}
